package day3.datasource;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

public class MyDatasource {
	
	private static final String url="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8";
	private static final String user="root";
	private static final String password="root";
	 
	
	private int minLinkCount=5;
	private int maxLinkCount=20;
	private int currentLinkCount=0;
	
	static {
		String className="com.mysql.jdbc.Driver";
		try {
			Class.forName(className);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new ExceptionInInitializerError(e);
		}
	}
	
	LinkedList<Connection> connectionPool=new LinkedList<Connection>();
	
	public MyDatasource() throws SQLException{
		for(int i=0;i<minLinkCount;i++){
			connectionPool.add(createConnection());
		}
	}
	
	private Connection createConnection() throws SQLException{
		return DriverManager.getConnection(url, user, password);
	}
	
	public Connection getConnection() throws SQLException{
		if(currentLinkCount>maxLinkCount){
			throw new RuntimeException("没有新的链接可用 ");
		}else{
			currentLinkCount++;
			if(connectionPool.size()>0){
				Connection connection=connectionPool.remove(0);
				return connection;
			}else{
				return createConnection();
			}
		}
	}
	
	public void free(Connection con){
		connectionPool.addLast(con);
	}
	
}
